import * as moment from "moment-timezone";
import KWContext from '../common/context';
import { SERVER_TIMEZONE } from "../constants";
import { parseId } from "../util/utilities";

//   日志
export default () => {
  return async (ctx: KWContext, next: any) => {
    const oid = parseId().toString();
    ctx.oid = oid;
    const url = ctx.request.originalUrl;
    const ip = ctx.request.headers['x-forwarded-for'] || ctx.req.connection.remoteAddress;
    const method = ctx.request.method;
    const agent = ctx.request.header['user-agent'];
    const start = moment.tz(SERVER_TIMEZONE);
    await next();
    const uid = ctx.query['uid'];
    const cost = moment.tz(SERVER_TIMEZONE).valueOf() - start.valueOf();
    let message = "", code = 200;
    if (ctx.response.body) {
      ctx.response.body[`oid`] = oid;
      ctx.response.body[`st`] = moment.tz(SERVER_TIMEZONE).unix();
      message = ctx.response.body['message'];
      code = ctx.response.body['code'];
    }
    const params = JSON.stringify(Object.assign(ctx.query, ctx.request.body));
    const loggerInformation = `${ctx.oid} ${start.format('YYYY-MM-DD.HH:mm:ss')} ${method} ${url} ${code} ${message} ${cost}ms ${uid} ${ip} ${agent}
    params: ${params}`;
    console.log(loggerInformation);
  };
}
